package com.xmzs.midjourney.service.impl;

import com.xmzs.common.core.utils.MapstructUtils;
import com.xmzs.common.mybatis.core.page.TableDataInfo;
import com.xmzs.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.xmzs.midjourney.domain.bo.MjRoomBo;
import com.xmzs.midjourney.domain.vo.MjRoomVo;
import com.xmzs.midjourney.domain.MjRoom;
import com.xmzs.midjourney.mapper.MjRoomMapper;
import com.xmzs.midjourney.service.IMjRoomService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * MJ创作会话Service业务层处理
 *
 * @author Lion Li
 * @date 2023-08-09
 */
@RequiredArgsConstructor
@Service
public class MjRoomServiceImpl implements IMjRoomService {

    private final MjRoomMapper baseMapper;

    /**
     * 查询MJ创作会话
     */
    @Override
    public MjRoomVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询MJ创作会话列表
     */
    @Override
    public TableDataInfo<MjRoomVo> queryPageList(MjRoomBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MjRoom> lqw = buildQueryWrapper(bo);
        Page<MjRoomVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询MJ创作会话列表
     */
    @Override
    public List<MjRoomVo> queryList(MjRoomBo bo) {
        LambdaQueryWrapper<MjRoom> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<MjRoom> buildQueryWrapper(MjRoomBo bo) {

        LambdaQueryWrapper<MjRoom> lqw = Wrappers.lambdaQuery();

        lqw.eq(bo.getExpirationDate() != null, MjRoom::getExpirationDate, bo.getExpirationDate());
        return lqw;
    }

    /**
     * 新增MJ创作会话
     */
    @Override
    public Boolean insertByBo(MjRoomBo bo) {
        MjRoom add = MapstructUtils.convert(bo, MjRoom.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改MJ创作会话
     */
    @Override
    public Boolean updateByBo(MjRoomBo bo) {
        MjRoom update = MapstructUtils.convert(bo, MjRoom.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MjRoom entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除MJ创作会话
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
